//
//  AppDelegate.m
//  rrqs
//
//  Created by kyjun on 16/3/23.
//
//

#import "AppDelegate.h"
#import <RESideMenu/RESideMenu.h>

#import "LeftController.h"
#import "HomeController.h"
#import "Location.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AFNetworking/AFNetworkActivityIndicatorManager.h>
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <IQKeyboardManager/IQToolbar.h>
#import <AdSupport/AdSupport.h>

// 引入 JPush 功能所需头文件
#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif


@interface AppDelegate ()<RESideMenuDelegate,JPUSHRegisterDelegate>
{
    NSTimer* _timer;
    BOOL _isSys;
}
@property (nonatomic, copy) NSString *fileName;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    // [self launchScreen];
    [self settingsGlobalStyle];
    [self locationManger:launchOptions];
    
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:[[HomeController alloc] init]];
    LeftController *leftMenuViewController = [[LeftController alloc] init];
    
    RESideMenu *sideMenuViewController = [[RESideMenu alloc]
                                          initWithContentViewController:navigationController
                                         leftMenuViewController:leftMenuViewController
                                                                   rightMenuViewController:nil];
    //      sideMenuViewController.backgroundImage = [UIImage imageNamed:@"Stars"];
    sideMenuViewController.menuPreferredStatusBarStyle = 1;
    sideMenuViewController.delegate = self;
    sideMenuViewController.contentViewShadowColor = [UIColor whiteColor];
    sideMenuViewController.contentViewShadowOffset = CGSizeMake(0, 0);
    sideMenuViewController.contentViewShadowOpacity = 0.6;
    sideMenuViewController.contentViewShadowRadius = 12;
    sideMenuViewController.contentViewShadowEnabled = YES;
    sideMenuViewController.scaleContentView = NO;
    sideMenuViewController.contentViewInLandscapeOffsetCenterX = Menu_CenterWidth;
    sideMenuViewController.contentViewInPortraitOffsetCenterX  = Menu_CenterWidth;
    sideMenuViewController.scaleContentView = NO;
    sideMenuViewController.scaleMenuView = NO;
    sideMenuViewController.panGestureEnabled = NO;

    
    self.window.rootViewController = sideMenuViewController;
    [self.window makeKeyAndVisible];
    
    [self startJPush:launchOptions];
    [self setUpFixiOS11]; //适配IOS 11

    [AMapServices sharedServices].apiKey = @"f48903c237707f8cd56f355cdaf8b190";
    return YES;
}
#pragma mark - 适配
- (void)setUpFixiOS11
{
    if (@available(ios 11.0,*)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        UITableView.appearance.estimatedRowHeight = 0;
        UITableView.appearance.estimatedSectionFooterHeight = 0;
        UITableView.appearance.estimatedSectionHeaderHeight = 0;
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    
    [JPUSHService setBadge:0];
    
    /* if ([CLLocationManager significantLocationChangeMonitoringAvailable])
     {
     [[Location sharedManager].locationManager stopUpdatingLocation];
     [[Location sharedManager ].locationManager startMonitoringSignificantLocationChanges];
     NSLog(@"Significant location change monitoring is available.");
     }
     else
     {
     NSLog(@"Significant location change monitoring is not available.");
     }*/
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    
    [JPUSHService setBadge:0];
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationRefreshNewTask object:nil];

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    /*if ([CLLocationManager significantLocationChangeMonitoringAvailable])
     {
     [[Location sharedManager].locationManager stopUpdatingLocation];
     [[Location sharedManager ].locationManager startMonitoringSignificantLocationChanges];
     NSLog(@"Significant location change monitoring is available.");
     }     else     {
     NSLog(@"Significant location change monitoring is not available.");
     }*/
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required
    [JPUSHService handleRemoteNotification:userInfo];
    [self handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    [self handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
}
#endif

-(void)settingsGlobalStyle{
    
    [UINavigationBar appearance].barStyle = UIBarStyleDefault;
    [UINavigationBar appearance].translucent = NO;
    // 设置导航栏背景颜色
    [UINavigationBar appearance].barTintColor =  theme_navigation_color;
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
     [UINavigationBar appearance].titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]}; // title颜色
    
    [[UITableView appearance] setBackgroundColor:theme_table_bg_color];
    [[UICollectionView appearance] setBackgroundColor:theme_table_bg_color];
    
    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    [[IQToolbar appearance] setBarTintColor:theme_navigation_color];
    [[IQToolbar appearance] setTintColor:theme_default_color];
    
}

-(void)locationManger:(NSDictionary *)launchOptions{
    
    [Location sharedManager];
}

#pragma mark =====================================================  RESideMenu Delegate

- (void)sideMenu:(RESideMenu *)sideMenu willShowMenuViewController:(UIViewController *)menuViewController
{
    NSLog(@"willShowMenuViewController: %@", NSStringFromClass([menuViewController class]));
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationUpdateUserAccount object:nil];
}

- (void)sideMenu:(RESideMenu *)sideMenu didShowMenuViewController:(UIViewController *)menuViewController
{
    NSLog(@"didShowMenuViewController: %@", NSStringFromClass([menuViewController class]));
}

- (void)sideMenu:(RESideMenu *)sideMenu willHideMenuViewController:(UIViewController *)menuViewController
{
    NSLog(@"willHideMenuViewController: %@", NSStringFromClass([menuViewController class]));
}

- (void)sideMenu:(RESideMenu *)sideMenu didHideMenuViewController:(UIViewController *)menuViewController
{
    NSLog(@"didHideMenuViewController: %@", NSStringFromClass([menuViewController class]));
}

#pragma mark =====================================================  设置极光推送
-(void)startJPush:(NSDictionary*)launchOptions{
    
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // 3.0.0及以后版本注册
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|UNAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
}

#pragma mark =====================================================  远程通知
/**
 *  接收通知
 *
 *  @param remoteInfo
 */
-(void)handleRemoteNotification:(NSDictionary *)remoteInfo{
    
    NSLog(@"通知:%@",remoteInfo);
    if(![WMHelper isNULLOrnil:remoteInfo]){
    
        if([[MSingle shareAuhtorization].userInfo.close isEqualToString:@"1"]){
            
            //            [self PayAudio:@"push_by_system.mp3"];

            NSDictionary *alert = remoteInfo[@"aps"][@"alert"];
            NSString *status = [NSString stringWithFormat:@"%@",alert[@"status"]];

            NSDictionary* notificationType = [remoteInfo objectForKey:@"aps"];
            if([[notificationType objectForKey:@"sound"] isEqualToString:@"push_new_order.mp3"]){//订单
                _isSys = NO;
                if (![[NSUserDefaults standardUserDefaults] boolForKey:@"DINGDANXIAOXI_LINGSHENG"] && [[NSUserDefaults standardUserDefaults] boolForKey:@"DINGDANXIAOXI_ZHENDONG"] ) {
                    [self PayAudio:@"push_new_order.mp3"];
                    //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  // 震动
                } else {
                    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"DINGDANXIAOXI_LINGSHENG"]) {//铃声默认
                        [self PayAudio:@"push_new_order.mp3"];
                    } else {//
                        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DINGDANXIAOXI_ZHENDONG"]) {//震动
                            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  // 震动
                        }
                    }
                }

            }else if([[notificationType objectForKey:@"sound"] isEqualToString:@"push_new_order.mp3"]){//系统
                _isSys = YES;
                if (![[NSUserDefaults standardUserDefaults] boolForKey:@"XITONGXIAOXI_LINGSHENG"] && [[NSUserDefaults standardUserDefaults] boolForKey:@"XITONGXIAOXI_ZHENDONG"] ) {
                    [self PayAudio:@"push_new_order.mp3"];
                    //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  // 震动
                } else {
                    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"XITONGXIAOXI_LINGSHENG"]) {//铃声默认
                        [self PayAudio:@"push_new_order.mp3"];
                    } else {//
                        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"XITONGXIAOXI_ZHENDONG"]) {//震动
                            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  // 震动
                        }
                    }
                }
            }else{
                
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationHomeRefreshing object:@{@"status":status}];
            
        }
    }

}

//
//-(void)PayAudio:(NSString*)fileName{
//    SystemSoundID soundID;
//    NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
//    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
//    AudioServicesPlaySystemSound(soundID);
//    /*AudioServicesPlaySystemSoundWithCompletion*/
//    AudioServicesPlayAlertSoundWithCompletion(soundID, ^{
//        //        self.contentHandler(self.bestAttemptContent);
//    });
//}

static NSInteger t = 0;
-(void)PayAudio:(NSString*)fileName{
    t=0;
    [_timer invalidate];
    self.fileName = fileName;
    _timer = [NSTimer scheduledTimerWithTimeInterval:8.0 target:self selector:@selector(Timered:) userInfo:nil repeats:YES];
}

- (void)Timered:(NSTimer*)timer {
    if (t== 2) {
        [_timer invalidate];
    } else {
        SystemSoundID soundID;
        NSString *path = [[NSBundle mainBundle] pathForResource:self.fileName ofType:nil];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
        
        if (_isSys) {
            if (![[NSUserDefaults standardUserDefaults] boolForKey:@"XITONGXIAOXI_LINGSHENG"] && [[NSUserDefaults standardUserDefaults] boolForKey:@"XITONGXIAOXI_ZHENDONG"] ) {
                AudioServicesPlayAlertSound(soundID);
            } else {
                AudioServicesPlaySystemSound(soundID);
            }
        } else {
            if (![[NSUserDefaults standardUserDefaults] boolForKey:@"DINGDANXIAOXI_LINGSHENG"] && [[NSUserDefaults standardUserDefaults] boolForKey:@"DINGDANXIAOXI_ZHENDONG"] ) {
                AudioServicesPlayAlertSound(soundID);
            } else {
                AudioServicesPlaySystemSound(soundID);
            }
        }
        AudioServicesPlayAlertSoundWithCompletion(soundID, ^{
            AudioServicesDisposeSystemSoundID(soundID);
            t++;
        });
    }
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
//前台收到远程通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        [self handleRemoteNotification:userInfo];
    
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

/// 点击通知栏消息相应方法
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        [self jumpHomeWithNotification:userInfo];
        
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif

-(void)jumpHomeWithNotification:(NSDictionary *)userInfo{
    
    NSLog(@"------------------%@",userInfo);
    NSDictionary *alert = userInfo[@"aps"][@"alert"];
    NSString *status = [NSString stringWithFormat:@"%@",alert[@"status"]];
    
    
    RESideMenu *VC =(RESideMenu *)self.window.rootViewController;
    UINavigationController *naviVc = (UINavigationController *)VC.contentViewController;
    //回退到指定界面
    for (UIViewController *vc in [naviVc viewControllers]) {//遍历一路跳转到本界面以来的所有界面
        //判断要回退的指定界面是否与遍历的界面相同
        if ([vc isKindOfClass:[HomeController class]]) {
            
            [naviVc popToViewController:vc animated:YES];//执行回退动作
//            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationRefreshMainData object:nil];

            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationHomeRefreshing object:@{@"status":status}];

            
            
        }
    }
    

}


#ifdef __IPHONE_12_0
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
    NSString *title = nil;
    if (notification) {
        title = @"从通知界面直接进入应用";
    }else{
        title = @"从系统设置界面进入应用";
    }
    UIAlertView *test = [[UIAlertView alloc] initWithTitle:title
                                                   message:@"pushSetting"
                                                  delegate:self
                                         cancelButtonTitle:@"yes"
                                         otherButtonTitles:nil, nil];
    [test show];
    
}
#endif



@end
